/*
 * Copyright (C) 2019 ByteDance Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bytedance.scene.utlity;

import ohos.agp.components.Component;

/**
 * Created by JiangQi on 8/19/18.
 */
public class SoftInputUtility {

    public static void hideSoftInputFromWindow(Component component) {
        if(component!=null){
            clearFocus(component);
        }
    }

    //clearFocus等同于隐藏软键盘
    public static void clearFocus(Component component){
        Component focusedComponent = findFocus(component, Component.FOCUS_NEXT);//尝试向后找焦点控件
        if (focusedComponent != null) {
            focusedComponent.clearFocus();
            return;
        }

        focusedComponent = findFocus(component, Component.FOCUS_PREVIOUS);//尝试向前找焦点控件
        if (focusedComponent != null) {
            focusedComponent.clearFocus();
        }
    }

    //找焦点控件
    public static Component findFocus(Component component, int direction){
        if (component.hasFocus()) {
            return component;
        }
        Component focusableComponent = component;
        int i = 99;
        while (i-->0){
            focusableComponent = focusableComponent.findNextFocusableComponent(direction);
            if (focusableComponent != null) {
                if (focusableComponent.hasFocus()) {
                    return focusableComponent;
                }
            } else {
                break;
            }
        }
        return null;
    }


}
